package com.example.demo.service.impl;

import com.example.demo.entity.Admin; // 新增导入
import com.example.demo.entity.User;
import com.example.demo.repository.AdminRepository; // 新增导入
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority; // 新增导入
import org.springframework.security.core.authority.SimpleGrantedAuthority; // 新增导入
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList; // 新增导入
import java.util.Collections; // 新增导入
import java.util.List; // 新增导入

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private AdminRepository adminRepository; // 新增注入

    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        // 尝试加载普通用户
        User user = userRepository.findByAccount(account).orElse(null);
        if (user != null) {
            // 为普通用户可以不指定角色，或者指定 "ROLE_USER"
            // 这里我们返回空权限列表，具体权限控制依赖于路径配置
            return new org.springframework.security.core.userdetails.User(
                    user.getAccount(),
                    user.getPassword(),
                    Collections.emptyList() // 或者: Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
            );
        }

        // 如果不是普通用户，尝试加载管理员
        Admin admin = adminRepository.findByAccount(account).orElse(null);
        if (admin != null) {
            List<GrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN")); // 赋予管理员 "ROLE_ADMIN" 权限
            return new org.springframework.security.core.userdetails.User(
                    admin.getAccount(),
                    admin.getPassword(),
                    authorities
            );
        }

        throw new UsernameNotFoundException("用户或管理员未找到，账号: " + account);
    }
}
